from django.db.models import Q

from articles.serializers import ChannelSerializer, CommentSerializer, CommentSerializerList, CommentSerializerItem, \
    ArticleCommentSerialzier
from django.db import transaction
from django.http import JsonResponse
from rest_framework.decorators import action
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from rest_framework_jwt.authentication import jwt_decode_handler
from articles.models import Channel, Article, Comment
from articles.pages import PageNum
from user.models import User
from user.serializers import ArticleSerializer




# 3.1 频道列表(ok)
from articles.serializers import ChannelSerializer, ArticleSerializerForList, ArticleSerializerForCreate, \
    ArticleSerializerForDetail
from questions.models import Label
from user.serializers import ArticleSerializer


class ChannelList(ListAPIView):
    """左侧导航"""

    serializer_class = ChannelSerializer
    queryset = Channel.objects.all()
    pagination_class = PageNum



class MySearchView(ListAPIView):
    """搜索"""
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer
    pagination_class = PageNum

    def get_queryset(self):
        keyword = self.request.query_params.get('text')
        if keyword:
            return Article.objects.filter(Q(title__contains=keyword) | Q(content__contains=keyword))
        else:
            return Article.objects.all()

class ArticleViewSet(ModelViewSet):
    queryset = Article.objects.all()
    pagination_class = PageNum
    serializer_class = ArticleSerializer

    # 新建文章 /article/
    def create(self, request, *args, **kwargs):

        try:
            user = request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            request_params = request.data
            request_params['user'] = user.id
            serializer = ArticleSerializerForCreate(data=request_params)
            serializer.is_valid(raise_exception=True)
            article = serializer.save()
            return Response({'success': True, 'message': '发表成功', 'articleid': article.id})
        else:
            return Response({'success': False, 'message': '未登录'}, status=400)

    # 按频道获取文章列表 /article/{pk}/channel/
    @action(methods=['get'], detail=True, url_path="channel")
    def get_article_by_channel(self, request, pk):
        if pk == "-1":
            articles = self.get_queryset()
        else:
            channel = Channel.objects.get(id=pk)
            articles = self.get_queryset().filter(channel=channel)

        page = self.paginate_queryset(articles)
        s = ArticleSerializerForList(page, many=True)
        return self.get_paginated_response(s.data)

# 3.1 频道列表(ok)

# class ArticleListView(ModelViewSet):
    # permission_classes = [IsAuthenticated]
    # queryset = Article.objects.all()
    # serializer_class = ArticleSerializer

    # 3.4 根据频道ID获取文章详情信息(ok)
    def retrieve(self, request, *args, **kwargs):
        id = int(self.kwargs['pk'])
        article = Article.objects.get(id=id)
        serializer = ArticleSerializerForDetail(article)
        return Response(serializer.data)

    @action(methods=['put'], detail=True, url_path="collect")
    # 3.3 收藏文章(ok)
    def collect(self, request, pk):
        pk = int(pk)
        article = Article.objects.get(id=pk)
        if request.user.collected_articles.filter(id=pk):
            request.user.collected_articles.remove(article)
            return Response({'success': True, 'message': '取消收藏成功'})
        else:
            request.user.collected_articles.add(article)
            return Response({'success': True, 'message': '收藏成功'})
    @action(methods=['post'], detail=True)
    # 3.6 给文章发表一条评论，给评论进行评论也使用此接口(ok)
    def publish_comment(self, request, pk):
        try:
            user = request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            pk = int(pk)
            data = request.data
            article = Article.objects.get(id=pk)
            data['article'] = pk
            data['user'] = user.id
            serializer = ArticleCommentSerialzier(data=data)
            if serializer.is_valid():
                serializer.save()
            # comment.save()
            # 生成评论的时候，不要忘了给文章更新一次，因为文章表里有评论数参数，+1
            # Article.objects.filter(id=article.id).update(comment_count=Article['comment_count'] + 1)
            return Response({
                   "message": "评论成功",
                   'success': True
               })
        else:
            return Response({'success': False, 'message': '未登录'}, status=400)

